<template>
  <el-dialog :draggable="true" :title='dialogSelectTitle' v-model='dialogSelectVisible' width='55%'
    :before-close="handleClose" :close-on-click-modal='false'>
    <QueryBase style="width: 95%;">
      <template #search>
        <el-input :placeholder='searchNotice' v-model='searchKey' prefix-icon="el-icon-search"></el-input>
      </template>
      <template #searchBtn>
        <div></div>
      </template>
      <template #operation>
        <el-button type='info' @click="emits('giveUp')">取 消</el-button>
        <el-button type="primary" @click='handleSubmit'>确 定</el-button>
      </template>
      <!-- 表格部分 -->
      <el-table :data='table.tableData' style='width:100%' stripe row-key="loginid" ref="multipleTable" :border="true"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" align-center :reserve-selection="true" width="55"></el-table-column>
        <el-table-column align-center v-for='item in table.tableColumn' :key='item.indexName' :label='item.text'>
          <template #default='scope'>
            <span>{{ scope.row[item.indexName] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部按钮和页码部分 -->
      <div class='select-login-pn'>
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentPageChange"
          :current-page.sync="currentPage" :page-size='pageSize' :pager-count="5" :page-sizes="[10, 25, 50, 100]"
          layout="total, sizes, prev, pager, next" :total='totalLength'>
        </el-pagination>
      </div>
    </QueryBase>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getRoleAuth, getUsers } from '@/api/authorization';
import elHelper from '@/common/elHelper';
import { reactive, ref, defineProps, defineEmits, watch, nextTick, unref } from 'vue';
import QueryBase from '@/components/layout/QueryBase.vue';
import comFunc from '@/common/comFunc';

const props = defineProps(['showDialog', 'roles'])
const emits = defineEmits(['sureSelect', 'giveUp'])

const dialogSelectVisible = ref(false)
const dialogSelectTitle = ref('')
const table = reactive({
  tableData: [] as any[],
  tableColumn: [
    {
      text: '登录账号',
      indexName: 'loginid'
    },
    {
      text: '用户类型',
      indexName: 'usertype'
    },
    {
      text: '用户编号',
      indexName: 'userno'
    }
  ]
})
const searchKey = ref('')
const searchNotice = ref('')
const selectUser = ref<any>()
const currentPage = ref(0)
const pageSize = ref(0)
const totalLength = ref(0)
const isSearch = ref(false)
const filterData = ref<any>([])
const totalData = ref<any[]>()
const roleUsers = ref<any[]>()
const multipleTable = ref()

watch(() => props.showDialog, (val) => {
  dialogSelectVisible.value = val
  if (val) {
    // 将数据还原
    pageSize.value = 10
    currentPage.value = 1
    searchKey.value = ''
    selectUser.value = null
    getRoleInfo()
    searchNotice.value = '请输入账号名称'
    dialogSelectTitle.value = '选择登录账号'
  }
})
watch(() => searchKey.value, (val) => {
  // 当检索的内容为空时需要将表格的内容还原
  if (comFunc.nvl(val) === '') {
    pageSize.value = 10
    currentPage.value = 1
    totalLength.value = totalData.value?.length || 0
    isSearch.value = false
    // 调用方法进行页面渲染
    showData(totalData.value)
  } else {
    // 检索结果的数据存放在 filterData 中
    filterData.value = []
    totalData.value?.forEach((value, index) => {
      if (value.loginid.indexOf(searchKey.value) !== -1) {
        filterData.value.push(value)
      }
    })
    isSearch.value = true
    currentPage.value = 1
    totalLength.value = filterData.value.length
    // 调用方法进行页面渲染
    showData(filterData.value)
  }
})

const getRoleInfo = async () => {
  const loading = elHelper.showLoading()
  const re = await getRoleAuth(props.roles)
  if (re.isSuccess) {
    roleUsers.value = re.data.login
    selectUser.value = re.data.login.length
    getLoginUsers()
  }
  elHelper.closeLoading(loading)
}
const getLoginUsers = async () => {

  const re = await getUsers()
  if (re.isSuccess) {
    totalData.value = []
    re.data.forEach(item => {
      totalData.value?.push(item)
    })
    totalLength.value = totalData.value.length
    // 将页面的CheckBox取消选中
    multipleTable.value.clearSelection()
    // 调用方法进行页面渲染
    showData(totalData.value)
    // 如果该角色有对应的账号,需要选中
    if (roleUsers.value?.length) {
      roleUsers.value.forEach(val => {
        multipleTable.value.toggleRowSelection(val, true)
      })
    }
  }
}
const getRowKeys = (row) => {
  return 'loginid'
}
const handleSelectionChange = (rows) => {
  selectUser.value = rows
}
// 点击确定按钮时
const handleSubmit = () => {
  emits('sureSelect', selectUser.value)
}
// 底部页码的部分
const handleSizeChange = (val) => {
  pageSize.value = val
  // 需要判断是否是检索的数据
  if (isSearch.value) {
    showData(filterData)
  } else {
    showData(totalData)
  }
}
const handleCurrentPageChange = (val) => {
  currentPage.value = val
  // 需要判断是否是检索的数据
  if (isSearch) {
    showData(filterData)
  } else {
    showData(totalData)
  }
}
const handleClose = () => {
  emits('giveUp')
}
const showData = (myData) => {
  // 渲染表格的数据存放在 tableData 中
  table.tableData = []
  if (myData.length) {
    let from = (currentPage.value - 1) * pageSize.value
    let to = currentPage.value * pageSize.value
    if (to > myData.length) {
      to = myData.length
    }
    for (; from < to; from++) {
      table.tableData.push(myData[from])
    }
  }
}
</script>
<style lang="scss" scoped>
.select-login-pn {
  padding-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
